package com.micolor.logr.runtime.util;

import com.micolor.logr.runtime.entity.LogMessageChangeItem;
import com.micolor.logr.runtime.entity.LogMessageItem;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author EvanGe
 * @Type ClazzUtil.java
 * @Desc
 * @date 2024/7/8 15:32
 */
public class ClazzAndMapUtil {
    public static Map<String,Object>  transObjectToMap(Object object,boolean callSupper) throws IllegalAccessException{
        Map<String,Object> resultMap = new HashMap<>();
        Class<?> clazz = object.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            resultMap.put(field.getName(), field.get(object));
        }
        if(callSupper){
            for (Field field : clazz.getSuperclass().getDeclaredFields()) {
                field.setAccessible(true);
                resultMap.put(field.getName(), field.get(object));
            }
        }
        return resultMap;
    }

    public static List<LogMessageChangeItem> compareList(List<LogMessageItem> oldList, List<LogMessageItem> newList){
        List<LogMessageChangeItem> compareList = new ArrayList<>();
        for(LogMessageItem oldItem:oldList){
            LogMessageItem newItem = newList.stream().filter(item->item.getName().equals(oldItem.getName())).findFirst().orElse(null);
            if(newItem!=null){
                if(!oldItem.equals(newItem)){
                    LogMessageChangeItem logMessageChangeItem = getLogMessageChangeItem(oldItem, newItem);
                    compareList.add(logMessageChangeItem);
                }
            }
        }
        return compareList;
    }

    private static LogMessageChangeItem getLogMessageChangeItem(LogMessageItem oldItem, LogMessageItem newItem) {
        LogMessageChangeItem logMessageChangeItem = new LogMessageChangeItem();
        logMessageChangeItem.setName(oldItem.getName());
        logMessageChangeItem.setDesc(oldItem.getDesc());
        logMessageChangeItem.setOriginalValue(oldItem.getOriginalValue());
        logMessageChangeItem.setTransValue(oldItem.getTransValue());
        logMessageChangeItem.setNewTransValue(newItem.getTransValue());
        logMessageChangeItem.setNewOriginalValue(newItem.getOriginalValue());
        return logMessageChangeItem;
    }
}
